{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4e6fb88a",
   "metadata": {},
   "source": [
    "# 第7周\n",
    "* author:小邱同学\n",
    "* time：第7周周二上午\n",
    "* link: [百度AI开放平台_文字识别](https://ai.baidu.com/ai-doc/OCR/zk3h7xz52)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71c5ac66",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1fc3a979",
   "metadata": {},
   "source": [
    "# OCR 光学文字识别\n",
    "\n",
    "> 1.通用场景文字识别  \n",
    ">> 1) 通用文字识别  \n",
    ">> 2) 网络文字文字识别  \n",
    ">> 3) 手写文字识别  \n",
    ">> 4) 二维码识别  \n",
    "\n",
    "> 2. 卡片文本识别  \n",
    ">> 1) 身份证  \n",
    ">> 2) 银行卡  \n",
    "\n",
    "> 3.财务票据文字识别  \n",
    ">> 1) 增值税发票  \n",
    ">> 2) 火车票  "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1fff6c1b",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5743560d",
   "metadata": {},
   "outputs": [],
   "source": [
    "API Key=U5V5s0L2c8klhw5f45si1EuH\n",
    "Secret Key=tA4MooqrWhKpU6lu1DqthkPjtrlMaewo"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b6cc593",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e64a080",
   "metadata": {},
   "source": [
    "## 获取Access Token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a29d8a7b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.15d551fb23b0391091af3ad2d8c0614e.315360000.1965093606.282335-25948875', 'expires_in': 2592000, 'session_key': '9mzdWBQOK7cGFvHwxeoGUBcZQqRXMFPHunEUUj2pR/Yxt0P6Zu62V0NZh+xod3rYL0XkNkEr1wQ3QjlgRfMAXZwx9zsZ4g==', 'access_token': '24.cda44c8902e672bbe49688dcfe16d11b.2592000.1652325606.282335-25948875', 'scope': 'public vis-ocr_ocr brain_ocr_scope brain_ocr_general brain_ocr_general_basic vis-ocr_business_license brain_ocr_webimage brain_all_scope brain_ocr_idcard brain_ocr_driving_license brain_ocr_vehicle_license vis-ocr_plate_number brain_solution brain_ocr_plate_number brain_ocr_accurate brain_ocr_accurate_basic brain_ocr_receipt brain_ocr_business_license brain_solution_iocr brain_qrcode brain_ocr_handwriting brain_form brain_ocr_passport brain_ocr_vat_invoice brain_numbers brain_ocr_business_card brain_ocr_train_ticket brain_ocr_taxi_receipt vis-ocr_household_register vis-ocr_vis-classify_birth_certificate vis-ocr_台湾通行证 vis-ocr_港澳通行证 vis-ocr_机动车购车发票识别 vis-ocr_机动车检验合格证识别 vis-ocr_车辆vin码识别 vis-ocr_定额发票识别 vis-ocr_保单识别 vis-ocr_机打发票识别 vis-ocr_行程单识别 brain_ocr_vin brain_ocr_quota_invoice brain_ocr_birth_certificate brain_ocr_household_register brain_ocr_HK_Macau_pass brain_ocr_taiwan_pass brain_ocr_vehicle_invoice brain_ocr_vehicle_certificate brain_ocr_air_ticket brain_ocr_invoice brain_ocr_insurance_doc brain_formula brain_seal brain_ocr_facade brain_ocr_meter brain_doc_analysis brain_ocr_webimage_loc brain_ocr_medical_paper brain_ocr_doc_analysis_office brain_vat_invoice_verification brain_ocr_medical_detail brain_vehicle_registration_certificate brain_ocr_online_taxi_itinerary brain_ocr_multi_idcard brain_ocr_mixed_multi_vehicle brain_ocr_weigth_note brain_ocr_ multiple_invoice wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': 'e50220c77338607fcd0f5adf2deca756'}\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "\n",
    "\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'U5V5s0L2c8klhw5f45si1EuH',\n",
    "    'client_secret':'tA4MooqrWhKpU6lu1DqthkPjtrlMaewo'\n",
    "}\n",
    "\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "7fa070e7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.cda44c8902e672bbe49688dcfe16d11b.2592000.1652325606.282335-25948875'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "api_word = response.json()['access_token']\n",
    "api_word"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ed70e35",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81f7c6c6",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5603d33",
   "metadata": {},
   "source": [
    "## （一）通用文字识别（高精度版）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d423745c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'words': '树先生说：世间之所以有三人行'}, {'words': '必然有可爱，也必定有可恨'}, {'words': '必须有隐忍'}, {'words': 'The sfoy of lose'}], 'words_result_num': 4, 'log_id': 1513720786170742090}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用文字识别（高精度版）\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('tongyong.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':api_word,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44a73b06",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b29f9c2",
   "metadata": {},
   "source": [
    "## （二）手写文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ff786c96",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'location': {'top': 126, 'left': 79, 'width': 317, 'height': 30}, 'words': '星光啊,走过了几万光年,才能'}, {'location': {'top': 169, 'left': 83, 'width': 303, 'height': 30}, 'words': '被我们看见。我想做一颗星星,穿'}, {'location': {'top': 212, 'left': 86, 'width': 306, 'height': 28}, 'words': '透稀薄的孤独,披上厚厚的时间,'}, {'location': {'top': 256, 'left': 84, 'width': 301, 'height': 28}, 'words': '在无数个光怪陆离的宇宙昼夜之中'}, {'location': {'top': 294, 'left': 91, 'width': 299, 'height': 27}, 'words': '飞行,终于在某年某月某日,我的光'}, {'location': {'top': 332, 'left': 93, 'width': 305, 'height': 29}, 'words': '闪耀在地球的夜晚,只为你无意'}, {'location': {'top': 371, 'left': 94, 'width': 183, 'height': 27}, 'words': '间抬头的那一瞥。”'}, {'location': {'top': 396, 'left': 284, 'width': 99, 'height': 27}, 'words': '一晚风先生'}], 'words_result_num': 8, 'log_id': 1513721541984758181}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "手写文字识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('shouxie.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':api_word,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4923120f",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "445705f1",
   "metadata": {},
   "source": [
    "## （三）网络图片文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "90429c69",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'words': '爱妃接旨'}], 'words_result_num': 1, 'log_id': 1513724019930598578}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "网络图片文字识别\n",
    "'''\n",
    "\n",
    "request_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/webimage'\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('wangluo.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':api_word,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "527a0a00",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0a4f008",
   "metadata": {},
   "source": [
    "## （四）二维码识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5ea4aa37",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'codes_result': [{'text': ['欢迎来到动画世界'], 'type': 'QR_CODE'}], 'codes_result_num': 1, 'log_id': 1513725078019593081}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "二维码识别\n",
    "'''\n",
    "\n",
    "request_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode'\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('er.png', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':api_word,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08a3d8e9",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ca3233b",
   "metadata": {},
   "source": [
    "## （五）二维码识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "302832d4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': {'姓名': {'location': {'top': 110, 'left': 118, 'width': 72, 'height': 30}, 'words': '奥巴马'}, '民族': {'location': {'top': 152, 'left': 242, 'width': 62, 'height': 27}, 'words': '哈尼'}, '住址': {'location': {'top': 237, 'left': 113, 'width': 254, 'height': 63}, 'words': '盛顿特区宾夕法尼亚大道1600号白宫'}, '公民身份号码': {'location': {'top': 0, 'left': 0, 'width': 0, 'height': 0}, 'words': ''}, '出生': {'location': {'top': 194, 'left': 116, 'width': 187, 'height': 29}, 'words': '19610804'}, '性别': {'location': {'top': 154, 'left': 122, 'width': 23, 'height': 27}, 'words': '男'}}, 'words_result_num': 6, 'idcard_number_type': 0, 'image_status': 'unknown', 'log_id': 1513726661535409847}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "二维码识别\n",
    "'''\n",
    "\n",
    "request_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard'\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('sfz.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':api_word,\n",
    "    'image':img,\n",
    "    'id_card_side':'front',\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "407c747a",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2dbd1094",
   "metadata": {},
   "source": [
    "## （六）银行卡识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "fdde2486",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result': {'valid_date': '02/25', 'bank_card_number': '6259 6508 9111 6660', 'bank_name': '中国建设银行', 'bank_card_type': 2, 'holder_name': 'CHEN TA'}, 'direction': 0, 'log_id': 1513727565559729941}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "银行卡识别\n",
    "'''\n",
    "\n",
    "request_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard'\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('yhk.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':api_word,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "222b9031",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63a89cef",
   "metadata": {},
   "source": [
    "## （七）增值税发票识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "e6531497",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result_num': 43, 'words_result': {'AmountInWords': ')佰圆整', 'InvoiceNumConfirm': '', 'CommodityEndDate': [], 'CommodityVehicleType': [], 'CommodityStartDate': [], 'CommodityPrice': [{'row': '1', 'word': '5.0'}], 'NoteDrawer': '代理盒', 'SellerAddress': '龙星市家宝区菜1号1245868', 'CommodityNum': [{'row': '1', 'word': '1'}], 'SellerRegisterNum': '', 'MachineCode': '', 'Remarks': '', 'SellerBank': '', 'CommodityTaxRate': [{'row': '1', 'word': '3%'}], 'TotalTax': '1.00', 'InvoiceCodeConfirm': '3300083620', 'CheckCode': '', 'InvoiceCode': '3300083620', 'InvoiceDate': '2016年00月08日', 'PurchaserRegisterNum': '', 'InvoiceTypeOrg': '星增值税普通发票', 'OnlinePay': '', 'Password': '无1T70无77', 'Agent': '否', 'AmountInFiguers': '无', 'PurchaserBank': '', 'Checker': '黄海E', 'City': '', 'TotalAmount': '0.00', 'CommodityAmount': [{'row': '1', 'word': '130.00'}], 'PurchaserName': '个人', 'CommodityType': [], 'Province': '浙江', 'InvoiceType': '普通发票', 'SheetNum': '第二联：发票联', 'PurchaserAddress': '', 'CommodityTax': [{'row': '1', 'word': '5.50'}], 'CommodityPlateNum': [], 'CommodityUnit': [], 'Payee': '', 'CommodityName': [{'row': '1', 'word': '套'}], 'SellerName': '', 'InvoiceNum': '01234567'}, 'log_id': 1513728089733242132}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "增值税发票识别\n",
    "'''\n",
    "\n",
    "request_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice'\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('zzs.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':api_word,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42dbd54f",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4058e0ec",
   "metadata": {},
   "source": [
    "## （八）火车票识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "ad30570a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result_num': 13, 'words_result': {'id_num': '4114211992****4212', 'serial_number': '44231000010824B022092', 'ticket_num': 'U028534', 'seat_num': '04车019号中铺', 'time': '05:52', 'date': '2014年09月09日', 'name': '', 'destination_station': '上海', 'seat_category': '新空调硬卧', 'starting_station': '平顶山西', 'sales_station': '', 'train_num': 'K284', 'ticket_rates': '￥194.50元'}, 'direction': 0, 'log_id': 1513728284784022513}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "火车票识别\n",
    "'''\n",
    "\n",
    "request_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/train_ticket'\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('hcp.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':api_word,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "}\n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "45443735",
   "metadata": {},
   "source": [
    "&emsp;"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
